package com.shop.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.admin.dao.ShopAdminDao;
import com.shop.admin.entity.*;
import com.shop.admin.interceptors.JWTInterceptor;
import com.shop.admin.result.ApiResult;
import com.shop.admin.service.OrganizationService;
import com.shop.admin.service.ShopAdminService;
import com.shop.admin.service.SysRoleService;
import com.shop.admin.service.SysUserRoleService;
import com.shop.admin.utils.PageUtils;
import com.shop.admin.utils.Query;
import com.shop.admin.utils.jwtUtils;
import com.shop.admin.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ShopAdminServiceImpl extends ServiceImpl<ShopAdminDao, ShopAdmin> implements ShopAdminService {

    @Autowired
    ShopAdminDao shopAdminDao;

    @Resource
    private OrganizationService organizationService;

    @Resource
    private ShopAdminService shopAdminService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Override
    public Object AdminLogin(Map<String, String> map) {

        if (map.isEmpty()) return ApiResult.fail("请输入用户名和密码！");

        QueryWrapper<ShopAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("admin_user", map.get("adminUser"))
                .eq("admin_password",map.get("adminPassword"));
        ShopAdmin shopAdmin = shopAdminDao.selectOne(queryWrapper);


        if ( shopAdmin != null ){
            //清空密码
            shopAdmin.setAdminPassword(null);
            // 生成jwt令牌
            String token =  jwtUtils.getToken( JSONObject.parseObject(JSON.toJSONString( shopAdmin )) );
            AdminTokenVo adminTokenVo = new AdminTokenVo();
            adminTokenVo.setToken(token);
            adminTokenVo.setOrgId(shopAdmin.getOrgId().intValue());
            adminTokenVo.setId(shopAdmin.getId().intValue());
            return ApiResult.ok("登陆成功",adminTokenVo);
        }

        return ApiResult.fail("用户名或密码错误！");
    }

    @Override
    public List<AdminVo> adminlist(Map<String, Object> params) {
        List<ShopAdmin> list = this.list(new QueryWrapper<ShopAdmin>().lambda().select(ShopAdmin::getId, ShopAdmin::getAdminName,ShopAdmin::getReceiveEmail,ShopAdmin::getOrgId).eq(ShopAdmin::getOrgId,params.get("orgId")).eq(ShopAdmin::getStatus,1));
        List<AdminVo> collect = list.stream().map(vo -> {
            AdminVo adminVO = new AdminVo();
            BeanUtils.copyProperties(vo, adminVO);
            return adminVO;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void adminMailChange(Integer adminId,Integer receiveEmail) {
        this.update(new LambdaUpdateWrapper<ShopAdmin>().eq(ShopAdmin::getId,adminId).set(ShopAdmin::getReceiveEmail,receiveEmail));
    }

    @Override
    public PageUtils adminSchoolList(Map<String, Object> params) {
        List<Organization> organizations = organizationService.list(new LambdaQueryWrapper<Organization>().select(Organization::getId, Organization::getOrgName).eq(Organization::getFatherId,0));
        List<SchoolOrgAdminVo> schoolOrgAdminVos = organizations.parallelStream().map(item -> {
            SchoolOrgAdminVo schoolOrgAdminVo = new SchoolOrgAdminVo();
            schoolOrgAdminVo.setSchoolName(item.getOrgName());
            BeanUtils.copyProperties(item, schoolOrgAdminVo);
            return schoolOrgAdminVo;
        }).collect(Collectors.toList());
        List<SchoolOrgAdminVo> orgAdminVos = schoolOrgAdminVos.parallelStream().map(item -> {
            List<Organization> organizations1 = organizationService.list(new LambdaQueryWrapper<Organization>().eq(Organization::getFatherId, item.getId()));
            SchoolOrgAdminVo schoolOrgAdminVo = new SchoolOrgAdminVo();
            BeanUtils.copyProperties(item, schoolOrgAdminVo);
            List<SchoolOrgAdminVo.OrgAdminVo> list = new ArrayList<>();
            for (Organization o : organizations1) {
                if (o.getFatherId().equals(item.getId())) {
                    SchoolOrgAdminVo.OrgAdminVo orgAdminVo = new SchoolOrgAdminVo.OrgAdminVo();
                    orgAdminVo.setOrgId(o.getId());
                    orgAdminVo.setOrgName(o.getOrgName());
                    List<ShopAdmin> shopAdmins = shopAdminService.list(new LambdaQueryWrapper<ShopAdmin>()
                            .select(ShopAdmin::getId, ShopAdmin::getAdminUser, ShopAdmin::getAdminName, ShopAdmin::getAdminMail, ShopAdmin::getReceiveEmail, ShopAdmin::getStatus, ShopAdmin::getOrgId, ShopAdmin::getCreateTime).eq(ShopAdmin::getOrgId, o.getId()));
                    List<SchoolOrgAdminVo.OrgAdminVo.shopAdminVo> collect = shopAdmins.stream().map(i -> {
                        SchoolOrgAdminVo.OrgAdminVo.shopAdminVo adminVo = new SchoolOrgAdminVo.OrgAdminVo.shopAdminVo();
                        BeanUtils.copyProperties(i, adminVo);
                        Integer fatherId = organizationService.getOne(new LambdaQueryWrapper<Organization>().eq(Organization::getId, i.getOrgId())).getFatherId();
                        adminVo.setFatherId(fatherId);
                        Integer roleId = sysUserRoleService.getOne(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, i.getId())).getRoleId();
                        SysRole sysRoleServiceOne = sysRoleService.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getId, roleId));
                        adminVo.setRoleId(sysRoleServiceOne.getId());
                        adminVo.setRoleName(sysRoleServiceOne.getRoleName());
                        adminVo.setRoleCode(sysRoleServiceOne.getRoleCode());
                        adminVo.setRoleCreateTime(sysRoleServiceOne.getCreateTime());
                        return adminVo;
                    }).collect(Collectors.toList());
                    orgAdminVo.setShopAdmins(collect);
                    list.add(orgAdminVo);
                    list.size();
                }
                schoolOrgAdminVo.setOrgAdminVos(list);
            }
            return schoolOrgAdminVo;
        }).collect(Collectors.toList());

        Page<SchoolOrgAdminVo> page = new Page<SchoolOrgAdminVo>(Long.parseLong(params.get("page").toString()),Long.parseLong(params.get("limit").toString()));
        page.setRecords(orgAdminVos);
        page.setTotal(orgAdminVos.size());
        PageUtils pageUtils=new PageUtils(page);
        return pageUtils;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ShopAdmin> page = this.page(
                new Query<ShopAdmin>().getPage(params),
                new QueryWrapper<ShopAdmin>().lambda().eq(ShopAdmin::getOrgId,params.get("orgId"))
        );
        return new PageUtils(page);
    }

    @Override
    public void adminStatus(AdminStatusVo statusVO) {
        ShopAdmin shopAdmin = new ShopAdmin();
        shopAdmin.setStatus(statusVO.getStatus());
        shopAdmin.setUpdateAdminId(statusVO.getUpdateAdminId());
        shopAdmin.setUpdateTime(new Date());
        this.update(shopAdmin,new QueryWrapper<ShopAdmin>().lambda().eq(ShopAdmin::getId,statusVO.getId()));
    }

    @Override
    public Object schoolLogin(Map<String, String> map) {
        if (map.isEmpty()) return ApiResult.fail("请输入用户名和密码！");

        if (!map.get("adminUser").equals("admin")) return ApiResult.fail("用户名不是学校管理员！");
        QueryWrapper<ShopAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ShopAdmin::getAdminUser,"admin")
                .eq(ShopAdmin::getAdminUser, map.get("adminUser"))
                .eq(ShopAdmin::getAdminPassword,map.get("adminPassword"));

        ShopAdmin shopAdmin = shopAdminDao.selectOne(queryWrapper);
        if ( shopAdmin != null ){
            //清空密码
            shopAdmin.setAdminPassword(null);
            // 生成jwt令牌
            String token =  jwtUtils.getToken( JSONObject.parseObject(JSON.toJSONString( shopAdmin )) );
            AdminTokenVo adminTokenVo = new AdminTokenVo();
            adminTokenVo.setToken(token);
            adminTokenVo.setOrgId(shopAdmin.getOrgId().intValue());
            adminTokenVo.setId(shopAdmin.getId().intValue());
            return ApiResult.ok("登陆成功",adminTokenVo);
        }
        return ApiResult.fail("用户名或密码错误！");
    }

    @Override
    public boolean selectBoolean(String adminUser,Long adminId) {
        QueryWrapper<ShopAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ShopAdmin::getAdminUser, adminUser)
                .ne(adminId != null, ShopAdmin::getId, adminId);
        int count = this.baseMapper.selectCount(queryWrapper);
        return count==0;
    }

    @Override
    public AdminNameVo getAdminName(Map<String, Object> params) {
        String adminId =  JWTInterceptor.userId;
        ShopAdmin admin = this.getById(Integer.parseInt(adminId));
        AdminNameVo adminNameVo = new AdminNameVo();
        BeanUtils.copyProperties(admin,adminNameVo);
        adminNameVo.setId(admin.getId().intValue());
        adminNameVo.setOrgId(admin.getOrgId().intValue());
        Organization organization = organizationService.getById(admin.getOrgId());
        adminNameVo.setOrgName(organization.getOrgName());
        Organization organizationServiceOne = organizationService.getOne(new QueryWrapper<Organization>().lambda().eq(Organization::getId, organization.getFatherId()));
        adminNameVo.setSchoolName(organizationServiceOne.getOrgName());
        return adminNameVo;
    }

    @Override
    public PageUtils adminSchoolListStream(Map<String, Object> params) {
//        List<ShopAdmin> shopAdmins = shopAdminService.list();
//        List<ShopAdmin> shopAdminList = shopAdmins.stream().filter(s -> s.getOrgId().equals(0)).collect(Collectors.toList());
//        List<SchoolOrgAdminStreamVo> schoolOrgAdminVos = shopAdminList.stream()
//                .collect(Collectors.groupingBy(
//                        shopAdmin -> Arrays.asList(shopAdmin.getId(), shopAdmin.getAdminName()),
//                        Collectors.mapping(
//                                shopAdmin -> shopAdmin.getId(),
//                                Collectors.toList()
//                        )
//                ))
//                .entrySet().stream()
//                .map(entry -> new SchoolOrgAdminVo(
//                        entry.getKey().get(0),
//                        entry.getKey().get(0),
//                        Collections.singletonList(new SchoolOrgAdminVo.OrgAdminVo(
//                                entry.getValue().stream()
//                                        .map(id -> new ShopAdmin(id,entry.getKey().get(1)))
//                                        .collect(Collectors.toList())
//                        ))
//                ))
//                .collect(Collectors.toList());
//        organizationService.list(new LambdaQueryWrapper<Organization>())
        return null;
    }


}

